<template>
  <div class="myOrder">
    <van-nav-bar
        title="我的订单"
        left-text="返回"
        left-arrow
        :placeholder="true"
        :safe-area-inset-top="true"
        @click-left="$router.back()"
    />
    <div class="blue"></div>
    <!--  地址列表  -->
    <div class="container" v-if="orderList">
      <van-tabs v-model="status" sticky animated @click="beforeChange">
        <van-tab v-for="(item,index) in tabs" :title="item.title">
          <div class="list" v-for="(items,index) in newOrderList" :key="index">
            <div class="oid">
              <div class="id">
                <span>{{ items.oid }}</span>
              </div>
              <div class="status">
                <span class="text" @click="receive(items.oid)">{{
                    items.status === 1 ? '确认收货' : items.status === 2 ? '已完成' : ''
                  }}</span>
                <van-icon v-if="items.status===2" @click="removeOrder(items.oid)" name="delete-o"></van-icon>
              </div>
            </div>
            <div v-for="(item,index) in items.list" :key="index" class="main">
              <div class="center">
                <div class="left">
                  <img :src="item.smallImg" class="auto-img">
                </div>
                <div class="right">
                  <div class="top">
                    <span class="name">{{ item.name }}</span>
                    <span class="rule">{{ item.rule }}</span>
                  </div>
                  <div class="eName">
                    <span>{{ item.enname|enName }}</span>
                  </div>
                  <div class="bom">
                    <div class="price">
                      <span>￥</span>
                      <span>{{ item.price }}</span>
                    </div>
                    <div class="num">
                      <span>x</span>
                      <span>{{ item.count }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="last">
              <div class="time">
                <span>{{ items.createdAt }}</span>
              </div>
              <div class="numAprice">
                <div class="num">
                  <span>共计</span>
                  <span>{{ items.totalItemsCount }}</span>
                  <span>件</span>
                </div>
                <div class="price">
                  <span>合计&nbsp;&nbsp;￥</span>
                  <span>{{ items.totalItemsPrice }}</span>
                </div>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>

  </div>
</template>

<script>
import {findOrder, receive, removeOrder} from "@/api/my";

export default {
  name: "myOrder",
  data() {
    return {
      tokenString: "",
      status: 0,
      orderList: [],
      newOrderList: [],
      tabs: [
        {title: '全部', status: 0},
        {title: '进行中', status: 1},
        {title: '已完成', status: 2},
      ]
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.tokenString = this.$cookies.get("tokenString");
      this.findOrder();
    },
    // 查询订单接口
    findOrder() {
      let self = this;
      let data = {
        appkey: self.appkey,
        tokenString: self.tokenString,
        status: self.status
      }
      findOrder(data).then(res => {
        if (res.data.code === 70000) {
          self.orderList = res.data.result
          self.datas()
        }
      })
    },
    datas() {
      // 使用对象进行提取相同oid的项目
      let mergedData = {};
      for (let i = 0; i < this.orderList.length; i++) {
        let item = this.orderList[i];
        let oid = item.oid;
        if (!mergedData.hasOwnProperty(oid)) {
          mergedData[oid] = {
            oid: oid,
            status: item.status,
            totalItemsCount: 0, // 新增属性，用于存储 count 的总和
            totalItemsPrice: 0,
            createdAt: this.formatDate(item.createdAt), // 转换为格式化后的日期字符串
            list: []
          };
        }
        mergedData[oid].list.push(item);
        mergedData[oid].totalItemsCount += item.count;
        mergedData[oid].totalItemsPrice += parseFloat(item.price); // 累加 price 的值，使用 parseFloat 进行转换
      }
      // 转换为数组形式
      let mergedArray = Object.values(mergedData);
      for (let i = 0; i < mergedArray.length; i++) {
        mergedArray[i].totalItemsPrice = mergedArray[i].totalItemsPrice.toFixed(2)
      }

      this.newOrderList = mergedArray
    },
    formatDate(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(date.getHours());
      const minutes = this.padZero(date.getMinutes());
      const seconds = this.padZero(date.getSeconds());
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    padZero(num) {
      return num.toString().padStart(2, '0');
    },
    // 进行切换选项卡
    beforeChange(index) {
      this.status = index;
      this.findOrder();
    },
    // 确认收货接口
    receive(oid) {
      let self = this;
      let data = {
        appkey: this.appkey,
        tokenString: this.tokenString,
        oid: oid
      }
      receive(data).then(res => {
        if (res.data.code === 80000) {
          self.$toast.success('收货成功！');
          self.findOrder();
        } else {
          self.$toast.fail('状态异常，请重新登录！');
          self.$router.push('/login')
        }
      })
    },
    // 删除订单
    removeOrder(oid) {
      let self = this;
      let data = {
        appkey: this.appkey,
        tokenString: this.tokenString,
        oid: oid
      }
      removeOrder(data).then(res => {
        if (res.data.code === 90000) {
          self.$toast.success('删除成功！');
          self.findOrder();
        } else {
          self.$toast.fail('状态异常，请重新登录！');
          self.$router.push('/login')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.myOrder {
  background: #f7f7f7;

  .blue {
    background: #0c34ba;
    width: 100%;
    height: 100px;
  }

  .container {
    margin: -20px 10px 0 10px;
    border-radius: 3%;
    padding: 5px;

    .list {
      background: #ffffff;
      margin: 15px 0;
      padding: 5px 10px;
      border-radius: 10px;

      .oid {
        display: flex;
        justify-content: space-between;
        color: #222222;
        margin: 10px 0;
        align-items: center;

        .id {
          font-size: 15px;
        }

        .status {
          .text {
            font-size: 14px;
            margin-right: 5px;
          }
        }
      }

      .main {
        .center {
          display: flex;
          align-items: flex-start;

          .left {
            flex: 3;
          }

          .right {
            flex: 7;
            margin-left: 10px;

            div {
              margin: 5px 0;

            }

            .top {

              span {
                margin-right: 5px;
              }

              .rule {
                font-size: 14px;
                color: #999999;
              }
            }

            .eName {
              color: #777777;
            }

            .bom {
              display: flex;
              justify-content: space-between;

              .price {
                font-weight: bold;
                color: #0c34ba;
                font-size: 16px;
              }

              .num {
                color: #888888;
              }
            }
          }
        }
      }

      .last {
        border-top: 1px dashed black;
        margin: 10px 0;

        .time {
          color: #888888;
          margin-top: 8px;
        }

        .numAprice {
          display: flex;
          justify-content: space-between;
          margin-top: 8px;

          .num {
            color: #888888;
            font-size: 15px;
          }

          .price {
            font-weight: bolder;
            font-size: 17px;
            color: #0c34ba;
          }
        }
      }
    }
  }


}

/deep/ .van-tabs__line {
  position: absolute;
  bottom: 15px;
  left: 0;
  z-index: 1;
  width: 40px;
  height: 3px;
  background-color: #0c34ba;
  border-radius: 3px;
}

/deep/ .van-tab--active {
  color: #0c34ba;
  font-weight: 500;
}

/deep/ .van-tabs__nav--line {
  border-radius: 15px;
}
</style>
